package com.itheima.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.Employee;
import com.itheima.pojo.PageBean;
import com.itheima.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小帅蓝
 * @Date 2022/6/12 15:07
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RedisTemplate<Object, Object> redis;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee) {
        //2.将密码进行MD5哈希
        //password = DigestUtils.md5DigestAsHex(password.getBytes());
        Employee e = employeeService.login(employee);

        if (ObjectUtil.isNull(e)) {
            return R.error("登录失败!");
        }
        //7.存在，生成token，存入redis，返回登录成功结果
        String token = System.currentTimeMillis() + e.getId();
        //7.1token加密
        token = DigestUtils.md5DigestAsHex(token.getBytes());
        //7.2，token作为key，用户信息作为value存入redis
        redis.opsForValue().set(TokenConstant.EMPLOYEE_TOKEN_PREFIX + token
                , JSON.toJSONString(e), 60 * 60, TimeUnit.SECONDS);
        //7.3返回登录成功结果
        e.setToken(token);
        return R.success(e);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        String authorization = request.getHeader("Authorization");
        redis.delete(authorization);
        ArrayList<String> list = new ArrayList<>();
        return R.success("退出成功");
    }

    @PostMapping
    public R<Employee> addEmployee(@RequestBody Employee employee) {
        return employeeService.addEmployee(employee);
    }

    @GetMapping("/page")
    public R<PageBean> queryAll(String name, Integer page, Integer pageSize) {
        PageBean pageBean = employeeService.queryAll(name, page, pageSize);
        if (pageBean != null) {
            return R.success(pageBean);
        } else {
            return R.error("查询失败！");
        }
    }

    @GetMapping("/{id}")
    public R<Employee> queryById(@PathVariable("id") String id) {
        Employee employee = employeeService.queryById(id);
        if (employee != null) {
            return R.success(employee);
        } else {
            return R.error("id不存在！");
        }
    }

    @PutMapping
    public R<Employee> updateEmployee(@RequestBody Employee employee) {
        return employeeService.updateEmployee(employee);
    }
}
